<?php

// +----------------------------------------------------------------------
// | 支付宝处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\notify;

use alipay\Trade;
use app\pay\event\Pay as PayEvent;
use think\facade\Config;
use think\facade\Env;
use think\facade\Log;
use wechat\mch\Pay as WechatPay;
use app\pay\model\Payment as PaymentModel;
use app\model\pay\Pay as PayModel;
use app\model\ucenter\User as UserModel;
use app\event\pos\PosOrder as PosOrderEvent;

class Alipay extends Common
{


    /**
     * @return string|void
     * 'gmt_create' => '2024-10-08 14:26:12',
     * 'charset' => 'UTF-8',
     * 'seller_email' => '2098557710@qq.com',
     * 'subject' => 'vip',
     * 'sign' => 'cU9FMIWpmZURyhoXsAtbzrEfi636wejDWzduxpM6MlsLhm2SSJFUxyI2GY4OEMrVeVF/5ns88tghBI8JBv0csADHduq+/Xz3Cm/XEIJ8HzpeF9afYrRnQMNi1PUZO6kFaAugiYg5dpNnYFGwUUHWG3elX/LiiogRnwFHRek27t66pOZpPLFWbghH5WoERSP7s/wyBRsrfwjUu6+QZHmXRCOlafvWG1r1rP3VDXj5dw6sjVBE19y8OvVLVwnwllEtHCre01ZNT4z5fnbWJDWceVn+vD8+v5JZre15ngqnAaMB1L2Xqo2I+1Xonzl36ZPiyi/+7jtGM7kNeXr7kk7TeQ==',
     * 'buyer_open_id' => '0297AUyntXQuJMjY8gZdGsgRlRYQXNHg4a5tiG2FUCK2r4b',
     * 'invoice_amount' => '0.01',
     * 'notify_id' => '2024100801222142614022291499611202',
     * 'fund_bill_list' => '[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]',
     * 'notify_type' => 'trade_status_sync',
     * 'trade_status' => 'TRADE_SUCCESS',
     * 'receipt_amount' => '0.01',
     * 'app_id' => '2021004181661289',
     * 'buyer_pay_amount' => '0.01',
     * 'sign_type' => 'RSA2',
     * 'seller_id' => '2088941431977212',
     * 'gmt_payment' => '2024-10-08 14:26:13',
     * 'notify_time' => '2024-10-08 14:51:17',
     * 'merchant_app_id' => '2021004181661289',
     * 'passback_params' => 'merchantBizType%3d3C%26merchantBizNo%3d2016010101111',
     * 'version' => '1.0',
     * 'out_trade_no' => '1728368763',
     * 'total_amount' => '0.01',
     * 'trade_no' => '2024100822001422291434009655',
     * 'auth_app_id' => '2021004181661289',
     * 'buyer_logon_id' => '139****7675',
     * 'point_amount' => '0.00',
     */
    public function pay()
    {
        if ($this->request->param('out_trade_no', '')) {
            // 支付成功
            $param = $this->request->except(['controller', 'action']);
//                $pa = '{"gmt_create":"2024-10-08 14:26:12","charset":"UTF-8","seller_email":"2098557710@qq.com","subject":"vip","sign":"cU9FMIWpmZURyhoXsAtbzrEfi636wejDWzduxpM6MlsLhm2SSJFUxyI2GY4OEMrVeVF\/5ns88tghBI8JBv0csADHduq+\/Xz3Cm\/XEIJ8HzpeF9afYrRnQMNi1PUZO6kFaAugiYg5dpNnYFGwUUHWG3elX\/LiiogRnwFHRek27t66pOZpPLFWbghH5WoERSP7s\/wyBRsrfwjUu6+QZHmXRCOlafvWG1r1rP3VDXj5dw6sjVBE19y8OvVLVwnwllEtHCre01ZNT4z5fnbWJDWceVn+vD8+v5JZre15ngqnAaMB1L2Xqo2I+1Xonzl36ZPiyi\/+7jtGM7kNeXr7kk7TeQ==","buyer_open_id":"0297AUyntXQuJMjY8gZdGsgRlRYQXNHg4a5tiG2FUCK2r4b","invoice_amount":"0.01","notify_id":"2024100801222142614022291499611202","fund_bill_list":"[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","app_id":"2021004181661289","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088941431977212","gmt_payment":"2024-10-08 14:26:13","notify_time":"2024-10-08 14:51:17","merchant_app_id":"2021004181661289","passback_params":"merchantBizType%3d3C%26merchantBizNo%3d2016010101111","version":"1.0","out_trade_no":"1728368763","total_amount":"0.01","trade_no":"2024100822001422291434009655","auth_app_id":"2021004181661289","buyer_logon_id":"139****7675","point_amount":"0.00"}';
//                $param = json_decode($pa,true);
            Log::write(json_encode($param));
            file_put_contents('./alipaynotify.txt', '信息收到 :' . json_encode($param) . "\r\n\r\n", FILE_APPEND);
            if (check_alipay($param)) {
                $pay = PayModel::where('pay_sn', $param['out_trade_no'])->find();
                if ($pay) {
                    $pay['api_amount'] = $param['total_amount'];
                    $pay['api_buyer_id'] = $param['buyer_logon_id'];
                    $pay['api_pay_status'] = $param['trade_status'];
                    $pay['api_pay_no'] = $param['trade_no'];
                    $pay['appid'] = $param['auth_app_id'];
                    if ($pay['api_pay_status'] == 'TRADE_SUCCESS' || $pay['api_pay_status'] == 'TRADE_FINISHED') {
                        $pay['status'] = 1;
                        $pay['pay_time'] = time_format();
                        if ($pay->save()) {
                            if ($pay['type'] == 'deposit') {
                                $user = UserModel::where('id', $pay['user_id'])->find();
                                if ($user['level']  !=2) {
                                    $user['level'] = 2;
                                    $user['deposit'] = $pay['total_amount'] +$user['deposit'];
                                    $user->save();
                                } 
                                // 开通vip
                                Log::write('开通VIP1');
                            } if ($pay['type'] == 'vip') {
                                $user = UserModel::where('id', $pay['user_id'])->find();
                                $user['level'] = 2;
                                $user->save();
                                // 开通vip
                                Log::write('开通VIP');
                            } elseif ($pay['type'] == 'pos') {
                                Log::write('购买pos');
                                $event = new PosOrderEvent();
                                $event->pay($pay);
                            } else {
                                // 开通vip
                                Log::write('未知');
                            }
                        } else {
                            return 'FAIL';
                        }
                    } else {
                        return 'FAIL';
                    }
                    return 'SUCCESS';
                } else {
                    return 'FAIL';
                }

            } else {
                return 'SUCCESS';
            }
            Log::write('支付宝异步信息：' . var_export($param, true));
        } else {
            Log::write('支付宝异步信息验证失败');
            return 'FAIL';
        }
    }


    public function refund()
    {
        $pay = \app\pay\model\Pay::where('id', 334)->find();
        // 支付成功
        $event = new PayEvent();
        $result = $event->refund($pay);
        dump($result);
        Log::write('支付宝异步信息：' . var_export($result, true));

    }

    public function h5()
    {
        $pay = PayModel::where('pay_sn', $this->request->param('pay_sn'))->where('status', 0)->find();
        if ($pay) {
            if ($pay['user_id'] == 16006 || $pay['user_id'] == 16013) {
                return alipay_h5_pay($pay['pay_sn'], 0.03, $pay['title'], $pay['type']);
            } else {
                return alipay_h5_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type']);
            }
        } else {
            return 'fail';
        }
    }


    public function transfer()
    {
        $pay = \app\pay\model\Pay::where('id', 334)->find();
        // 支付成功
        $event = new PayEvent();
        $result = $event->transferAlipay('alipay_web', time(), 'lilwil@163.com', 0.01, '刘伟');
        dump($result);
        Log::write('支付宝异步信息：' . var_export($result, true));

    }


    public function wechat()
    {
        libxml_disable_entity_loader(true);
        $pay = new WechatPay;
        $data = $pay->saveData(file_get_contents('php://input'));
        Log::record('微信通知信息：' . var_export($data, true));
        if ($pay->checkSign()) {
            $data['attach'];
            $event = new PayEvent();
            $result = $event->check($data);
            Log::record('支付运算信息：' . var_export($result, true));
            $pay->setReturnParameter('return_code', 'SUCCESS'); // 设置返回码
            $pay->setReturnParameter('return_msg', 'OK'); // 返回信息
        } else {
            $pay->setReturnParameter('return_code', 'FAIL'); // 返回状态码
            $pay->setReturnParameter('return_msg', '签名失败'); // 返回信息
            Log::record('微信验证签名失败：' . var_export($data, true));
        }
        Log::record('返回' . $pay->returnXml());
        return $pay->returnXml();
    }
}
